import sys
from polyglot import aggregator
from humanize import naturaltime

def render_table(table):
    def column_break(widths):
        out = "-"
        for w in widths:
            out += "-" * (w + 2) + "-"

        return out + "\n"

    box_widths = [max(map(len, col)) for col in zip(*table)]

    out = column_break(box_widths)
    for row in table:
        out += "|"
        for col, width in zip(row, box_widths):
            out += " " + col.ljust(width) + " |"
        out += "\n" + column_break(box_widths)

    return out

def render_grade_summary(s):
    return str(s * 100) + "%" if s is not None else "N/A"

if len(sys.argv) < 5:
    print("usage: report-frontend.py BACKEND USERNAME PASSWORD SCHOOL", file=sys.stderr)
    exit(1)

backend = aggregator.load_backend(sys.argv[1])
config = {
    "Email": sys.argv[2],
    "Username": sys.argv[2],
    "Password": sys.argv[3],
    "School": sys.argv[4]
}

aggregator.authenticate(backend, config)
courses = backend.courses

print(render_table([("Class", "Grade")] + [(c.title, render_grade_summary(c.grade_summary)) for c in courses]))

tasks = []
for course in courses:
    tasks += [(course.title, task.name, naturaltime(task.due_date)) for task in course.tasks]

print(render_table([("Class", "Name", "Due")] + tasks))
